/*
 * Powered By [pkuWx]
 * Web Site: http://www.wuxi.ss.pku.edu.cn
 * Since 2015 - 2015
 */

package cn.edu.pku.wxlib.category.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.pku.wxlib.category.dao.CategoryDao;
import cn.edu.pku.wxlib.category.model.Category;
import cn.edu.pku.wxlib.category.vo.query.CategoryQuery;
import cn.edu.pku.wxlib.vo.response.CategoryFull;
import javacommon.base.BaseManager;
import javacommon.base.EntityDao;
import javacommon.page.Page;

/**
 * @version 1.0
 * @since 1.0
 */

@Service
@Transactional
public class CategoryManager extends BaseManager<Category, CategoryQuery, java.lang.Integer>
		implements CategoryService {

	@Autowired
	private CategoryDao categoryDao;

	public void setCategoryDao(CategoryDao dao) {
		this.categoryDao = dao;
	}

	public EntityDao getEntityDao() {
		return this.categoryDao;
	}

	@Transactional(readOnly = true)
	public Page findPage(CategoryQuery query) {
		return categoryDao.findPage(query);
	}

	@Transactional(readOnly = true)
	public CategoryFull findChildrenCategoryByRootCategory(CategoryQuery query) {
		List<CategoryFull> lists = this.categoryDao.findChildrenCategorysList(query);

		Map<Integer, CategoryFull> hashmap = new HashMap<Integer, CategoryFull>();
		CategoryFull category = null;
		// 散列所有区域
		for (CategoryFull a : lists) {

			if (!hashmap.containsKey(a.getParentCategoryId())) {
				category = new CategoryFull();
				hashmap.put(a.getParentCategoryId(), category);
			} else {
				category = hashmap.get(a.getParentCategoryId());
			}
			category.getChildrens().add(a);
		}

		// 将根节点连接起来
		Iterator<Integer> iterator = hashmap.keySet().iterator();
		while (iterator.hasNext()) {
			CategoryFull a = hashmap.get(iterator.next());

			for (CategoryFull item : a.getChildrens()) {
				if (hashmap.containsKey(item.getCategoryId())) {
					CategoryFull temp = hashmap.get(item.getCategoryId());
					item.setChildrens(temp.getChildrens());
					hashmap.put(item.getCategoryId(), item);
				}
			}
		}
		return hashmap.get(query.getParentCategoryId());
	}
}
